package com.shengzai.flink.sink

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.connector.base.DeliveryGuarantee
import org.apache.flink.connector.kafka.sink.{KafkaRecordSerializationSchema, KafkaSink}
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}

object Demo2KafkaSink {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val studentDS: DataStream[String] = env.readTextFile("data/students.txt")

    /**
     * 将数据写入kafka
     */

    val kafkaSink: KafkaSink[String] = KafkaSink
      .builder[String]()
      .setBootstrapServers("master:9092,node1:9092,node2:9092") // kafka 集群列表
      .setRecordSerializer(KafkaRecordSerializationSchema
        .builder[String]()
        .setTopic("student")
        .setValueSerializationSchema(new SimpleStringSchema()) //序列化类
        .build()
      )
      //数据处理的语义，AT_LEAST_ONCE：  至少一次
      .setDeliverGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
      .build()

    //使用kafka sink
    studentDS.sinkTo(kafkaSink)

    env.execute()

  }

}
